package com.yiren.dbaa.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

import com.yiren.dbaa.R;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

/**
 * Created by WANGRONGXIANG
 * on 2022/5/19
 * Describe
 */
public class NumberEdittext extends androidx.appcompat.widget.AppCompatEditText implements TextWatcher, View.OnFocusChangeListener {

    private Context context;

    private float min;        //最小值
    private float max;        //最大值
    private int defaultValue; //editText默认值
    private String text;
    private boolean isMatch;  //输入的值是否匹配

    public NumberEdittext(Context context) {
        this(context, null);
    }

    public NumberEdittext(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NumberEdittext(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.numberEdittext);
        min = a.getFloat(R.styleable.numberEdittext_min, 0);
        max = a.getFloat(R.styleable.numberEdittext_max, 0);
        defaultValue = a.getInt(R.styleable.numberEdittext_defaultValue, 0);
        addTextChangedListener(this);
        setOnFocusChangeListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        text = s.toString();
        if (StringUtils.isNotEmpty(text)) {
            float value = Float.parseFloat(text);
            if (value >= min && value <= max) {
                isMatch = true;
                return;
            }
        }
        isMatch = false;
        MessageBox.show(context, "请输入" + min + "-" + max + "内的值！");
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            if (!isMatch) {
                this.setText(defaultValue + "");
            }
        }

    }

}
